package com.kuang.user.controller;

import com.kuang.bascic.Myexception.BusinessException;
import com.kuang.bascic.utils.AjaxResult;
import com.kuang.jwt.PayloadData;
import com.kuang.jwt.RsaUtils;
import com.kuang.jwt.UserInfo;
import com.kuang.org.domain.Employee;
import com.kuang.org.mapper.EmployeeMapper;
import com.kuang.system.domain.Menu;
import com.kuang.system.mapper.MenuMapper;
import com.kuang.system.mapper.PermissionMapper;
import com.kuang.user.domian.LoginInfo;
import com.kuang.user.domian.dto.UserDto;
import com.kuang.user.mapper.UserMapper;
import com.kuang.user.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.kuang.jwt.JwtUtils.generateTokenExpireInSeconds;

@RestController
public class LoginController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private UserMapper userMapper;
    @Value("${jwt.rsa.pri}")// SPEL表达式读取配置文件中的值
    private String jwtRsaPrivate;
    @PostMapping("/login")
    public  AjaxResult login(@RequestBody UserDto userDto){
        try {
//            LoginInfo loginInfo = loginService.loadAcount(userDto);
//
//            //将信息加入redis  返回给前端两个参数  一个是用户信息和模拟session的uuid 的随机token
//            String token = UUID.randomUUID().toString();
//            // 将信息加入到redis
//            redisTemplate.opsForValue().set(token,loginInfo,30, TimeUnit.MINUTES);
//            // 将数据返回给前端  这里正好使用上我们制作的工具类
//            Map<String, Object> map = new HashMap<>();
//            map.put("token",token);
//            map.put("loginInfo",loginInfo);
//            // 清空敏感数据
//            loginInfo.setPassword("");
//            loginInfo.setSalt("");
//          return  AjaxResult.me().setResultObj(map);
//        } catch (BusinessException e) {
//          return AjaxResult.me().setMessage(e.getMessage());
//        }catch (Exception e){
//            e.printStackTrace();
//            return AjaxResult.me().setMessage(e.getMessage());
//        }
            LoginInfo loginInfo = loginService.loadAcount(userDto);
            Map<String, Object> map = new HashMap<>();
            UserInfo userInfo = new UserInfo();
            userInfo.setLoginInfo(loginInfo);
            // 判断是否为主站
            if (loginInfo.getType()==1){
                // 主站用户直接放行
                map.put("loginInfo",loginInfo);
            }else {
                //非主站用户
                // 获取用户的 返回 menu菜单 所有权限
//                Employee employee = employeeMapper.selectEmployeeByLoginId(loginInfo.getId());
                List<Menu> menus = menuMapper.selecetMenusByLoginId(loginInfo.getId());
                List<String> sns = permissionMapper.selectPremission(loginInfo.getId());
                userInfo.setMenus(menus);
                userInfo.setSns(sns);
                // 获取私钥加密 获得token
                //3 token构造 redis token:jwt
                //3.1 获取私钥
                try {
                    // 获取到了私钥
                    PrivateKey privateKey = RsaUtils
                            .getPrivateKey(FileCopyUtils
                                    .copyToByteArray(this.getClass().getClassLoader().getResourceAsStream(jwtRsaPrivate)));
                    // 获取token
                    String token = generateTokenExpireInSeconds(userInfo, privateKey, 50000);
                    System.out.println(token);
                    loginInfo.setSalt("");
                    loginInfo.setPassword("");
                    map.put("loginInfo",loginInfo);
                    map.put("token",token);
                    map.put("menus",menus);
                    map.put("sns",sns);
                } catch (NoSuchAlgorithmException e) {
                    throw new RuntimeException(e);
                } catch (InvalidKeySpecException e) {
                    throw new RuntimeException(e);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }


            }
            return AjaxResult.me().setResultObj(map);


    }catch (BusinessException e){
//            return AjaxResult.me().setMessage(e.getMessage());
        }
        return null;
    }
}
